<?php

namespace app\acc\controller;

use think\Controller;
use think\Db;

class Prize extends Controller {

    /**
     * 每10分钟计算一次奖励
     *
     * 矿机收益算法：矿机token * 0.2% = 当天收益，（0.2%为后台设置，读取）
     *
     * 1.用户购买，上级获得收益的30%，直接充值到用户钱包，上级token为0，没有收益，有token减去相应toke
     * */

    //用户购机列表
    public function index(){
        //查询用户购买矿机列表
        $listMiners = Db::name('user_miner')->where(['status' => 1,'type' => 1])->order('id')->select();
        //查询已购买矿机列表
       /* $userMinersTotal = Db::name('user_miner')->where(['status' => 1,'type' => 1])->order('id')->count();
        for ($i = 0; $i < $userMinersTotal; $i++){

        }*/
        foreach ($listMiners as $k=>$v){
            //判断用户是否新购矿机
            if ($v['kj_already_token'] == '0.00'){
                $receive = $v['kj_token'] * $v['kj_token_speed']; //矿机日产收益
                $res = $this->countReceive($v['user_id'], $receive);
                if ($res){
                    unset($listMiners[$k]);
                    return;
                }else{

                }
            }else{

            }
        }
    }

    /**
     * 计算收益
     * $receive 为当前新购矿机产生收益
     * */
    public function countReceive($user_id, $receive){
        $user = Db::name('member')->field('id,parentId,all_receive')->find($user_id);
        //查询该用户的上级用户
        $userParent = Db::name('member')->field('id,miner,parentId,kj_all_token,all_receive,max_calculation')->find($user_id);
        if (!empty($userParent)){
            //判断用户的总token是否小于收益，如果是不增加收益，返回
            if ($userParent['kj_all_token'] < $receive){
                return true;
            }else{
                $receive = ( $user['all_receive'] + $receive ) * 0.3;
                //增加收益，直接提至用户矿池钱包
                $dataUser['miner'] = $userParent['miner'] + $receive;
                //减少用户总token
                $dataUser['kj_all_token'] = $userParent['kj_all_token'] - $receive;
                //增加用户总收益
                $dataUser['all_receive'] =  $userParent['all_receive'] + $receive;
                //更新用户数据
                Db::where('id',$userParent['id'])->save($dataUser);
                //继续执行，查找该用户上级用户
                $this->countReceive($userParent['id'],$receive);
            }
        }else{
            //已无上级用户，直接返回
            return true;
        }

    }

}
